package com.alan.product.issue.service.impl;

import com.alan.product.issue.entity.Item;
import com.alan.product.issue.entity.ItemFlow;
import com.alan.product.issue.entity.ItemWarehouses;
import com.alan.product.issue.mapper.ItemFlowMapper;
import com.alan.product.issue.mapper.ItemMapper;
import com.alan.product.issue.service.ItemService;
import com.alan.product.issue.util.LockUtil;
import com.alan.product.issue.util.TransacationHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ItemFlowMapper itemFlowMapper;

    @Autowired
    private TransacationHelper transacationHelper;

    @Autowired
    private ItemService self;

    @Override
    public String editItem(Long id, String name) {
        // item: 1 aa 2
        // item: 1 bb 2
        LockUtil.lock("item_" + id, () -> {
            Item item = itemMapper.selectById(id);
            String originalName = item.getName();
            item.setName(name);

            String remark = "修改商品名称，原名称为：" + originalName + "，修改为：" + name;

            // 调用统一的更新商品方法
            self.updateItem(item, 1, remark);
            /// ...
        });

        return "success";
    }

    @Override
    @Transactional
    public void updateItem(Item item, Integer opCode, String remark) {
        itemMapper.update(item);

        ItemFlow itemFlow = new ItemFlow();
        itemFlow.setItemId(item.getId());
        itemFlow.setOpCode(opCode);
        itemFlow.setRemark(remark);
        itemFlowMapper.insert(itemFlow);
    }

    @Override
    public String updateCount(Long id, Integer count) {
        // item: 1 aa 2
        // item: 1 aa 10
        // item: 1 bb 10
        LockUtil.lock("item_" + id, () -> {
            transacationHelper.tx(() -> {
                // item: 1 bb 2
                // item: 1 bb 10
                Item item = itemMapper.selectById(id);
                Integer originalCount = item.getCount();
                item.setCount(item.getCount() + count);
                itemMapper.update(item);

                ItemFlow itemFlow = new ItemFlow();
                itemFlow.setItemId(item.getId());
                itemFlow.setOpCode(2);
                itemFlow.setRemark("修改商品库存，原库存为：" + originalCount + "，增加库存：" + count);
                itemFlowMapper.insert(itemFlow);
            });
        });

        return "success";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editItemWarehouses(ItemWarehouses itemWarehouses) {
        itemMapper.deleteItemWarehouses(itemWarehouses.getItemId());
        itemMapper.insertItemWarehouse(itemWarehouses);
    }

}
